package in.co.codedoc.util;

import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Properties;

public class PropertiesUtil
{
	public static abstract class ForEach
	{
		public abstract void Do(String key,String value);
	}
	
	public static void ScanClassPath(String resourceName,ForEach forEach)
	{
		Logger.logger.info("Scanning classpath for " + resourceName);
		
		try
		{
			Properties entries = new Properties();

			HashSet<String> doneResources = new HashSet<String>();
			Enumeration<URL> resources
				= PropertiesUtil.class.getClassLoader().getResources(resourceName);

			while(resources.hasMoreElements())
			{
				URL resource = resources.nextElement();
				
				if(!doneResources.contains(resource.getFile()))
				{
					Logger.logger.debug("Loading " + resource.getFile());
						
					InputStream is = resource.openStream();
					
					entries.load(is);
					
					is.close();
					
					doneResources.add(resource.getFile());
				}
			}
			
			Enumeration<Object> keys = entries.keys();

			while(keys.hasMoreElements())
			{
				String key = keys.nextElement().toString();
				String value = entries.getProperty(key).toString();
			
				Logger.logger.debug("Key:" + key + ", Value:" + value);

				forEach.Do(key, value);
			}
		}
		catch (Throwable th)
		{
			throw new RuntimeException
			(
				"Failed while loading '" + resourceName + "' from classpath. Reason:"
					+ th.getMessage(),
				th
			);
		}
	}
}
